<!-- Amount Field -->
<label class="col-sm-3 control-label text-left" for="amount">
    Amount
    <a href="#" data-toggle="tooltip" title='This is the amount that you would like to use' class="pull-right" id="amount-tooltip"><i class="fa fa-lg fa-question-circle-o margin-top-5" ></i></a>
</label>
<div class="col-sm-9">
    <div class="input-group pull-left" style="width:223px" id="amount-wrapper">
        <input type="text" class="form-control" name="amount" id="amount" placeholder="0.00000000"  data-minlength="1" required >
        <a class="input-group-addon" id="amount-max">MAX</a>
    </div>
    <div class="input-group pull-right" style="width:180px" id="amount-value-wrapper">
        <a class="input-group-addon"><i class="fa fa-usd"></i></a>
        <input type="text" class="form-control" name="value" id="amount-value" placeholder="0.00" >
    </div>
</div>

<script>

// Function to calculate and set fiat value based on asset amount
function updateSendValue(amt){
    if(! $('#amount-value').prop('disabled')){
        var val = (FW.ASSET_INFO.estimated_value.btc *  numeral(amt).value()) * btc_info.price_usd;
        if(!isFinite(val))
            val = 0;
        $('#amount-value').val(numeral(val).format('0,0.00'));
    }
}

// Function to calculate and display asset amount based on fiat value
function updateSendAmount(val){
    var amt = ((numeral(val).value() / btc_info.price_usd) / FW.ASSET_INFO.estimated_value.btc),
        fmt = (FW.ASSET_INFO.divisible) ? '0,0.00000000' : '0,0',
        val = $('#available').val();
    // If we have an available amount field, rely on that to determine proper format
    if(val)
        fmt = (val.indexOf('.')!=-1) ? '0,0.00000000' : '0,0';
    if(!isFinite(amt))
        amt = 0;
    $('#amount').val(numeral(amt).format(fmt));
}

$(document).ready(function(){

    // Stash current price info on BTC and XCP
    var btc_info = getAssetPrice('BTC',true);
        xcp_info = getAssetPrice('XCP',true);
        type     = getFormType();
        tip      = $('#amount-tooltip');
    // Change the look/feel of the form based on form type
    if(type=='send'){
        // On the 'Send Funds' form, resize the fee fields a bit since less space is available
        $('#amount-wrapper').width(210);
        $('#amount-value-wrapper').width(170);
    } else if(type=='issue-supply'||type=='dividend'){
        // On the 'Issue Supply' form, disable the USD value field and hide 'Max' button
        $('#amount-value').attr('readonly', true);
        $('#amount-max').hide();
        $('#amount').addClass('input-rounded-right');
    } else if(type=='dispenser-buy'){
        // Update quantity to give_quantity
        $('#amount').val(FW.DIALOG_DATA.give_quantity);
    }

    // Wait a brief moment to allow things to initialize
    setTimeout(function(){

        // Change toolip text based on form type 
        var txt = false;
        if(type=='send')
            txt = 'This is the amount that you would like to send';
        if(type=='burn')
            txt = 'This is the amount that you would like to burn';
        if(type=='destroy')
            txt = 'This is the amount that you would like to destroy';
        if(type=='dividend')
            txt = 'This is the amount of dividend tokens that you would like to pay out per each unit';
        if(type=='issue-supply')
            txt = 'This is the amount of additional supply you would like to issue';
        if(type=='dispenser-buy')
            txt = 'This is the amount of ' + FW.DIALOG_DATA.name +' that you would like to buy';
        if(txt)
            tip.attr('data-original-title',txt);

        // Trigger change to calculate USD prices
        if(type=='dispenser-buy')
            $('#amount').change();

    },750);

    // Detect any amount change and format as valid number
    $('#amount').change(function(e){
        // Handle updating tx size as token name changes
        if(type=='dividend'||type=='burn'||type=='send'||type=='mint-supply')
            updateTransactionSize();
        var amt = String($(this).val()).replace(/[^0-9.]/g,''),
            val = $('#available').val(),
            fmt = (FW.ASSET_INFO.divisible) ? '0,0.00000000' : '0,0',
            o   = FW.DIALOG_DATA;
        // If we have an available amount field, rely on that to determine proper format
        if(val)
            fmt = (val.indexOf('.')!=-1) ? '0,0.00000000' : '0,0';
        // Force the amount to an increment of what the dispenser is selling
        if(type=='dispenser-buy'){
            var amt = numeral(amt).value(),
                min = numeral(o.give_quantity).value(),
                max = numeral(o.give_remaining).value(),
                sat = numeral(o.satoshirate).value();
            // Force minimum quantity to dispenser give amount
            if(amt < min)
                amt = min;
            // Force maximum quantity to what is available in the dispenser
            if(amt > max)
                amt = max;
            // Force quantity to a multiple of what the dispenser is offering (disable for now, got some complaints of issues)
            // if(amt % min && amt < max)
            //     amt = (amt - (amt % min));
            // Update the BTC amount to be based off the quantity
            var btc = numeral((amt / min) * sat).format('0,0.00000000');
            $('#btc-amount').val(btc);
            updateBTCValue(btc);
        }
        $(this).val(numeral(amt).format(fmt));
        updateSendValue(amt);
    });

    // Calculate the fiat value as the user types the amount
    $('#amount').keyup($.debounce(100,function(e){
        // Ignore tabs
        if(e.keyCode==9)
            return;
        var amt = String($(this).val()).replace(/[^0-9.]/g,'');
        updateSendValue(amt);
    }));

    // Make sure fiat value is in correct format
    $('#amount-value').change(function(e){
        var val = String($(this).val()).replace(/[^0-9.]/g,'');
        $(this).val(numeral(val).format('0,0.00'));
        updateSendAmount(val);
    });

    // Calculate the crypto value as the user types the fiat amount
    $('#amount-value').keyup($.debounce(100,function(e){
        // Ignore tabs
        if(e.keyCode==9)
            return;
        var amt = String($(this).val()).replace(/[^0-9.]/g,'');
        updateSendAmount(amt);
    }));

    // When user clicks 'Max' button, set amount to max available
    $('#amount-max').click($.debounce(100,function(e){
        var max   = String($('#available').val()).replace(/[^0-9.,]/g,''),
            asset = $('#token-name-select').val();
        // Deduct any miners fee from the max BTC send amount
        if(asset=='BTC'){
            var avail = numeral(max).format('0.00000000'),
                fee   = numeral($('#fee-amount').val()).format('0.00000000'),
                max   = numeral(avail).subtract(fee).format('0.00000000');
        }
        // For dispenser buys, force max to be max available in dispenser
        if(type=='dispenser-buy')
            max = FW.DIALOG_DATA.give_remaining;
        $('#amount').val(max).change();
        // If fiat field is not disabled, set fiat value as well
        if(! $('#amount-value').prop('disabled')){
            var max = String($('#available-value').val()).replace(/[^0-9.,]/g,'');
            $('#amount-value').val(max);
        }
    }));

});
</script>